package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleLikesMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleLikesService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleLikes;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApArticleLikesServiceImpl extends ServiceImpl<ApArticleLikesMapper, ApArticleLikes> implements ApArticleLikesService {
   @Resource
   private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult likeArticle(Integer userId, Long articleId, Boolean isLike) {
        // 参数校验
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (articleId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 检查文章是否存在
        ApArticle article = apArticleMapper.selectById(articleId);
        if (article == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        // 查询用户是否已点赞
        ApArticleLikes articleLike = getOne(new LambdaQueryWrapper<ApArticleLikes>()
                .eq(ApArticleLikes::getUserId, userId)
                .eq(ApArticleLikes::getArticleId, articleId));

        if (isLike) {
            // 点赞操作
            if (articleLike == null) {
                // 未点赞，执行点赞操作
                ApArticleLikes apArticleLikes = new ApArticleLikes();
                apArticleLikes.setUserId(userId);
                apArticleLikes.setArticleId(articleId);
                apArticleLikes.setIsLike((short) 1);
                apArticleLikes.setCreatedTime(new Date());
                apArticleLikes.setUpdatedTime(new Date());
                boolean save = save(apArticleLikes);

                if (save) {
                    // 增加文章点赞数
                    article.setLikes(article.getLikes() + 1);
                    apArticleMapper.updateById(article);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }
            } else if (articleLike.getIsLike() == 0) {
                // 已取消点赞，重新点赞
                articleLike.setIsLike((short) 1);
                articleLike.setUpdatedTime(new Date());
                boolean update = updateById(articleLike);

                if (update) {
                    // 增加文章点赞数
                    article.setLikes(article.getLikes() + 1);
                    apArticleMapper.updateById(article);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }
            }
        } else {
            // 取消点赞操作
            if (articleLike != null && articleLike.getIsLike() == 1) {
                // 已点赞，执行取消点赞操作
                articleLike.setIsLike((short) 0);
                articleLike.setUpdatedTime(new Date());
                boolean update = updateById(articleLike);

                if (update) {
                    // 减少文章点赞数
                    if (article.getLikes() > 0) {
                        article.setLikes(article.getLikes() - 1);
                        apArticleMapper.updateById(article);
                    }
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult isArticleLiked(Integer userId, Long articleId) {
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(articleId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if(apArticle == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticleLikes articleLike = getOne(new LambdaQueryWrapper<ApArticleLikes>()
                .eq(ApArticleLikes::getUserId, userId)
                .eq(ApArticleLikes::getArticleId, articleId));

        Map<String, Boolean> result = new HashMap<>();
        result.put("isLiked", articleLike != null && articleLike.getIsLike() == 1);

        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult getUserLikedArticles(Integer userId, Integer page, Integer size) {
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(page == null || size == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<ApArticleLikes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleLikes::getUserId, userId)
                .eq(ApArticleLikes::getIsLike, 1)
                .orderByDesc(ApArticleLikes::getCreatedTime);
        List<ApArticleLikes> articleLikes = list(queryWrapper);
        // 处理空列表情况
        if (articleLikes.isEmpty()) {
            Page<ApArticle> emptyPage = new Page<>(page, size);
            emptyPage.setRecords(new ArrayList<>());
            emptyPage.setTotal(0L);
            return ResponseResult.okResult(emptyPage);
        }
        List<Long> articleIds=articleLikes.stream().map(ApArticleLikes::getArticleId).collect(Collectors.toList());
        List<ApArticle> articles = apArticleMapper.selectBatchIds(articleIds);
        Page<ApArticle> pageParam = new Page<>(page, size);
        pageParam.setRecords(articles);
        pageParam.setTotal((long) articles.size());
        return ResponseResult.okResult(pageParam);
    }
}
